﻿//uses jquery

var kavadenn = kavadenn || {};

kavadenn.NETWORK_HELPER_MAX_RETRIES = 3;

kavadenn.doJSONPost = function(url, data, onOk, onError) {
    $.ajax({ type: "POST", dataType: "json",
        url: url,
        data: data,
        success: onOk,
        currentRetry: 0,
        error: function(xhr, status, err) {
            this.currentRetry++;

            if (this.currentRetry > kavadenn.NETWORK_HELPER_MAX_RETRIES) {
                if (onError != null) onError();
            }
            else {
                $.ajax(this);
            }
        }
    });
}


kavadenn.doJSONGet = function(url, data, onOk, onError) {
    $.ajax({ type: "GET", dataType: "json",
        url: url,
        data: data,
        success: onOk,
        currentRetry: 0,
        error: function(xhr, status, err) {
            this.currentRetry++;

            if (this.currentRetry > kavadenn.NETWORK_HELPER_MAX_RETRIES) {
                if (onError != null) onError();
            }
            else {
                $.ajax(this);
            }
        }
    });
}

// loads html content into the specified HTML element
// @targetElement is a jquery element to host the loaded content
kavadenn.loadContent = function(targetElement, url, onOk, onError) {
    $.ajax({ type: "GET", dataType: "html",
        url: url,
        success: function(content) {
            targetElement.html(content);
            if (onOk != null) onOk();
        },
        currentRetry: 0,
        error: function(xhr, status, err) {
            this.currentRetry++;

            if (this.currentRetry > kavadenn.NETWORK_HELPER_MAX_RETRIES) {
                targetElement.html("sorry, this content is currently not available");
                if (onError != null) onError();
            }
            else {
                $.ajax(this);
            }
        }
    });
}
